from kazoo.client import KazooClient
import urllib
import json
import types

from robot.api import logger
from robotlibcore import keyword
from robot.libraries.Telnet import TelnetConnection

from .JsonSchemaLib import JsonSchemaLib

class Dubbo(object):

    def __init__(self):

        self.schema = JsonSchemaLib()

    @keyword("Dubbo Invoke")
    def dubbo_invoke(self, zk_connect_url, interface_name, method_name, post_data, data_type="JsonObject"):
        """
        调用dubbo接口
        | Dubbo Invoke | "host=10.199.142.109,port=2181,group=business-test,version=1.0.0" | com.demo.interface | getUser| {"userId": 1}|
        """
        zk_connect_dict = {}
        provider = {}

        command_str = "invoke {0}.{1}({2})".format(interface_name, method_name, self._get_post_data(post_data, data_type))

        for i in zk_connect_url.split(",")[:]:
            k = i.split("=")[0]
            v = i.split("=")[1]
            zk_connect_dict[k] = v

        zkAddress = "{0}:{1}".format(zk_connect_dict['host'], zk_connect_dict['port'])
        group = zk_connect_dict['group']
        version = zk_connect_dict['version']
        logger.info("[Dubbo] zk地址: {0}, group: {1}, version: {2}".format(zkAddress, group, version))
    
        try:
            zk = KazooClient(hosts=zkAddress)
            zk.start()
            gg = zk.get_children("/dubbo/{}/providers".format(interface_name))
            # logger.info("[Dubbo] 服务节点: {}".format(gg))
            if gg:
                for i in gg:
                    url = urllib.parse.unquote(i)
                    # logger.info("[Dubbo] 服务节点: {}".format(url))
                    if url.startswith('dubbo:'):
                        if url.find("group={}".format(group)) > 0:
                            if url.find("version={}".format(version)) > 0:
                                data = url.split('?')[0].split('dubbo://')[1].split('/')[0]
                                logger.info("[Dubbo] 服务地址：{}".format(url))
                                provider["host"] = data.split(":")[0]
                                provider["port"] = data.split(":")[1]
        finally:
            zk.stop()
        # logger.info("[Dubbo] provide: {}".format(provider))

        logger.info("[Dubbo] 连接dubbo服务机器: {0}:{1} with prompt: dubbo>".format(provider['host'], provider['port']))

        conn = TelnetConnection(host=str(provider['host']), port=provider['port'], prompt='dubbo>')
        logger.info(("[Dubbo] 执行invoke命令: " + command_str))
        result = conn.write(command_str)

        logger.info(("[Dubbo] 关闭dubbo连接"))
        conn.close()

        data = json.loads(result)
        self.schema.create_schema(data)

        return data

    def _get_post_data(self, post_data, data_type):

        if data_type == "JsonObject":
            result = json.dumps(post_data)
        else:
            tmp = []
            for value in post_data.values():
                tmp.append(value)

            result = str(tmp).replace("None", "null").replace("[","").replace("]","")
        
        logger.info("[Dubbo] 请求参数: ({})".format(result))
        return result